{% extends 'base/base.html' %}
{% load my_filter %}
{% block js %}
    <script>
   $(function () {   // 正确简写，原写法 $(document).ready({...}) 会报错
    $('.collect').click(function () {
        const $img  = $(this);
        // 从 href="/user/detail/123/" 里抠出 123
        const id    = $img.closest('li').find('a').attr('href').match(/\d+/)[0];

        $.ajax({
            url: '/operate/collect/',
            method: 'post',
            data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                article: id     ,       // 动态 ID
                user: {{ request.user.id|default:0 }}  // 没登录给 0
            },
            success: function (data) {
                if (data.msg === '收藏成功') {
                    $img.attr('src', '/static/img/已收藏.png');  // 只改自己
                } else if (data.msg === '取消收藏成功') {
                    $img.attr('src', '/static/img/没收藏.png');
                }
            }
        });
    });
});

    </script>
{% endblock %}




{% block main %}

<div class="card p-4">
  <ul class="list-group list-group-flush">
 {% csrf_token %}
    {% for article in object_list %}
      <li class="list-group-item">
        <div class="d-flex justify-content-between align-items-start">
          <div class="me-3">
            <a class="h5 d-block mb-1 text-decoration-none" href="{% url 'user:detail' article.id %}">{{ article.title }}</a>
              {% if article|has_collect:request.user %}

              <img class="collect" src="/static/img/已收藏.png" alt="收藏" width="40" height="40">
              {% else %}
              <img class="collect" src="/static/img/没收藏.png" alt="收藏" width="40" height="40">
              {% endif %}




            <p class="m-0 muted">{{ article.content }}</p>
          </div>

        </div>
      </li>
    {% empty %}
      <li class="list-group-item">暂无文章</li>
    {% endfor %}
  </ul>
</div>
{% endblock %}